package no.ntnu.fp.connection;

import java.io.IOException;
import no.ntnu.fp.handler.Handler;
import no.ntnu.fp.net.co.Connection;


/**
 * This class implements the receiving end of a {@link Connection}, 
 * constantly listening for new messages and handling them appropriately
 * through the {@link Handler}s registered in {@link MessageHandler}.
 * It is designed for interruptability through calls to {@link Thread#interrupt()}
 * The static {@link ThreadLocal} field allows {@link Handler}s called through
 * message handling to access the {@link Connection} with which this {@code ReceiveWorker} interacts.
 * @author benjamin
 *
 */
public final class ReceiveWorker implements Runnable {

	private final Connection connection;
	private final MessageHandler messageHandler = MessageHandler.getInstance();

	private final static ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>(); 

	public ReceiveWorker(Connection connection) {
		this.connection = connection;
	}

	@Override
	public void run() {
		connectionHolder.set(connection);
		try {
			while (connection.isConnected()) {
				String message = connection.receive();
				System.err.printf("Got message %s in RW\n", message);
				messageHandler.handleMessage(message);
			}
		} catch (IOException ex) {
			try {
				connection.close();
			} catch (IOException e) {
				throw new RuntimeException("Reciveworker crash", e);
			}
		} catch (InterruptedException ex) {
			System.err.println("RW was interrupted: \n" + ex);
			Thread.currentThread().interrupt();
		}
	}
	/* catch (InterruptedException e) {
			connection.close();
			Thread.currentThread().interrupt();
		}*/


	public static synchronized Connection getThreadLocalConnection() {
		return connectionHolder.get();
	}
}